﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Fly.Common.Extensions
{
    /// <summary>
    /// DataTable 扩展方法
    /// </summary>
    public static class DataTableExtensions
    {
        /// <summary>
        /// 尝试获取 DataRow 对象中指定键的值，并转换为目标值，如果该值不存在或转换失败则返回默认值
        /// </summary>
        /// <typeparam name="T">转换目标数据类型</typeparam>
        /// <param name="dataRow">DataRow 对象</param>
        /// <param name="name">键名</param>
        /// <param name="defValue">返回的默认值</param>
        /// <returns></returns>
        public static T TryField<T>(this DataRow dataRow, string name, T defValue) where T : struct
        {

            if (dataRow == null || !dataRow.Table.Columns.Contains(name) || dataRow[name] == null){ return defValue;}
            return dataRow[name].ToString().TryParse(defValue);
        }
        /// <summary>
        /// 尝试获取 DataRow 对象中指定键的值并转换为字符串类型，如果该值不存在则返回默认值
        /// </summary>
        /// <param name="dataRow">DataRow 对象</param>
        /// <param name="name">键名</param>
        /// <param name="defValue">返回的默认值</param>
        /// <returns></returns>
        public static string TryField(this DataRow dataRow, string name, string defValue)
        {
            if (dataRow == null || !dataRow.Table.Columns.Contains(name) || dataRow[name] == null){ return defValue;}
            return dataRow[name].ToString();
        }
        /// <summary>  
        /// 将集合类转换成DataTable  
        /// </summary>  
        /// <param name="list">集合</param>  
        /// <returns></returns>  
        public static DataTable ListToDataTable(IList list)
        {
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }

                foreach (object t in list)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(t, null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }  
    }
}
